// JavaScript Document

var articles = {
	
	// stores a reference to the currently loaded article category for quick addition
	category_id: null,
	
	// stores a reference to the last selected category link
	lastCategoryLink: null,
	
	// parent ID of currently editted category
	lastCategoryParentID: null,
	
	// ajax page
	ajax_page : 'ajax_pages/articles.php',
	
	/**
	 * Initialises the articles object and attaches the necessary event handlers
	 */
	init: function() {
		
		pageManager.addEvent('add-cat-link','click',function(){
			articles.showDialogForAdd();
		});
		
		// register the event listener for the add category link
        pageManager.addEvent('edit-cat-link', 'click', function() {
            articles.showDialogForEdit();
        });
		
		pageManager.addEvent('del-cat-link', 'click', function() {
            articles.deleteArticleCategory();
        });
		
		pageManager.addEvent('cat-cancel-btn', 'click', function() {
			pageManager.hide("#cat-add-dialog");	
		});
		
		pageManager.addEvent('add-arts-link', 'click', function() {
			articles.addArticle();
		});
		
		pageManager.addEvent('del-arts-link', 'click', function() {
			articles.deleteArticles();
		});
		
		
		
		pageManager.all(".category-list li a", function(el) {
			el.onclick = function() {
				// load the articles in this category and indicate it as selected
				articles.loadArticles(this);
				
				return false;
			};
		});
		
		// create a UI Menu using the UI script framework
        var items_array = new Array();
        pageManager.all(".category-list li a", function(el, i) {
            var mi = {
                id: el.getAttribute("data-id"),
                name: el.innerHTML,
                title: el.title,

                // menus will call this action and supply the menu item as a parameter, so define the
                // action to use the supplied object
                action: function(mi) {
                    articles.moveArticlesToCategory( mi );
                }
            };

            items_array[i] = mi;
        });

        ui.menu( pageManager.$("#move-link"), {
            items: items_array
        });
		
		// load the articles in the first category
		var firstCat = pageManager.$(".category-list li:first-child a");
		if( firstCat ) {
			articles.loadArticles( firstCat );
		}
	},
	
	/**
	 * Loads the list of articles in the specified category
	 */
	loadArticles: function(catLink, page) {
		// if a category link is not specified, check if a previous one exists and use that instead
		if( catLink == null && articles.lastCategoryLink != null ) {
			catLink = articles.lastCategoryLink;	
		
		// if one does not exist, then inform and exit
		} else if( catLink == null && articles.lastCategoryLink == null) {
			alert('Cannot Load Articles If Category Link Is Not Specified');
			return;
		}
		
		// set a variable to determine the limit for the number of pages to load
        var limit = 25;
		
		// cache the currently selected category id
		articles.category_id = catId;
		
		//clear any previously selected list items
		if( articles.lastCategoryLink != null ) {
			articles.lastCategoryLink.parentNode.className = '';	
		}
		
		var catName = catLink.innerHTML;
		var catId = catLink.getAttribute("data-id");
		catLink.parentNode.className = 'selected';
		
		// cache the last category link
		articles.lastCategoryLink = catLink;
		
		// update the article list header
		document.getElementById("art-pane-header").innerHTML = 'Articles In ' + catName;
		
		// build the query to load the articles based on the category id
		var query = "action=load_articles&category=" + catId + "&limit=" + limit;
		
		// if a specific page is specified, then ammend the query to include that
        // also add the option to not reload the articles-total data so that the navigation
        // bar would not be regenerated
        if( page ) {
            query += "&start=" + page + "&no-total=true";
        }
		
		pageManager.setLoaderMessage("Loading Articles In " + catName + ". Please Wait...");
		pageManager.post('ajax_pages/articles.php', query, function(data) {

			$("#articles-display").html(data);
			
			// obtain the information about the total number of articles in this category
            // and generate a dynamic list of page links
            if( document.getElementById("articles-total") ) {
                var total = document.getElementById("articles-total").value;
                var total_pages = Math.ceil((total / limit));
				
                // get the footer pane and clear the contents
                var paneFooter = pageManager.$(".articles-pane .pane-footer");
                paneFooter.innerHTML = "<b>Pages: </b> ";
				
                for(var i = 0; i < total_pages; i++) {
                    var a = document.createElement("a");
                    a.setAttribute("href","#");
                    a.id = "page-" + i;
                    a.className = "nav-link";
					
                    // if this is the first link, then indicate that this is the selected page
                    if( i == 0 ) {
                        a.className = "selected";
                    }
					
                    a.innerHTML = (i + 1);
					
                    // add the necessary callback to the link to enable page loading
                    a.onclick = function() {
                        pageManager.all(".pane-footer a", function(el) {
                            el.className = "nav-link";
                        });
						
                        this.className = "selected";
						
                        var p = this.id.split("-")[1];
                        articles.loadArticles( articles.lastCategoryLink, p);
                    };
					
                    paneFooter.appendChild( a );
                }
            }
			
			// register the checkAll checkbox to be able to select all displayed messages
			pageManager.addEvent('checkAll', 'click', function() {
				
				// select all input fields in table-cells in the data-table component
				pageManager.all(".cms-data-table td input[type=checkbox]", function(el) {
					el.checked = pageManager.$('checkAll').checked;
				});
			});
			
			// register all edit-links
			pageManager.all(".cms-data-table .edit-link", function(el) {
				el.onclick = function(e) {
					articles.editArticle( this.id );
					return false;
				};
			});
						
			// register all edit-links
			pageManager.all(".cms-data-table .delete-link", function(el) {
				el.onclick = function(e) {
					articles.deleteArticle( this.id );
					return false;
				};
			});
			
			// register all the publish or unpublish-links
			pageManager.all(".cms-data-table .cms-publish-link, .cms-data-table .cms-unpublish-link", function(el) {
				el.onclick = function() {
					articles.publishArticle( this );
					return false;
				};
			});
		});
	},
	
	addArticle: function() {
		var setup_form = function() {
			// setup the tinyMCE HTML Editor for textareas
			articles.registerHTMLEditors();
			$("#ArticleTitle").friendurl({id:'ArticleTitleAlias'});	
			system.createPageLinkers();
			
			picup.init({
				targetDiv : "picupArea",
				pictureField : "ArticleImage",
				thumbField : "ArticleThumbnail",
				destFolder : "../assets/images/content/pics/",
				thumbFolder : "../assets/images/content/thumbs/",
				useSection: "articles"
			});	
		};
		
		var cancel_form = function() {
			// unregister the HTML Editors so as not to cause conflict on next add
			articles.unregisterHTMLEditors();
			
			// show the article categories and lists
			document.getElementById("editor-pane").style.display = "none";
			document.getElementById("content-pane").style.display = "table";
		};
		
		var query = "action=add_article";
		pageManager.post('ajax_pages/articles.php', query, '#editor-pane #pane-content', function(result) {
			// hide the content pane and show the editor
			document.getElementById("content-pane").style.display = "none";
			document.getElementById("editor-pane").style.display = "block";
			
			// setup the editor form
			setup_form();
			
			pageManager.addEvent("#editor-pane #can-art-btn",'click',function() {
				cancel_form();	
			});
			
			pageManager.addEvent("#editor-pane #sav-art-btn", 'click', function() {
				// ensure the tinyMCE editors save their content first
				tinyMCE.triggerSave();
				
				// run simple validation on the form
				if( !$p("#article-form").validate() ) {
					// prevent the dialog from closing if validation fails
					return false; 
				}
				
				// build a query of the data for submission
				var query = "action=create_article&CategoryID=" + articles.category_id + "&" + $p("#article-form").serialize();
				
				// submit the data
				pageManager.post('ajax_pages/articles.php', query, 'pm-pane-content', function() {
					// hide the dialog
					//pageManager.hideDialog();
					cancel_form();
					
					// reload the current category of articles
					var selected_cat_id = $p("#article-form #CategoryID").val();
					var al = $p(".category-list li a#cat-" + selected_cat_id ).node();
					articles.loadArticles( al );
				});
				
				// prevent the dialog from closing
				return false;
			});
		});
	},
	
	editArticle: function(id) {
		var setup_form = function() {
			// create page linkers
			system.createPageLinkers();
			
			// setup the tinyMCE HTML Editor for textareas
			articles.registerHTMLEditors();
			
			picup.init({
				targetDiv : "picupArea",
				imgPath: document.getElementById("ArticleThumbnail").value,
				pictureField : "ArticleImage",
				thumbField : "ArticleThumbnail",
				destFolder : "../assets/images/content/pics/",
				thumbFolder : "../assets/images/content/thumbs/",
				useSection: "articles"
			});	
		};
		
		var cancel_form = function() {
			// unregister the HTML Editors so as not to cause conflict on next add
			articles.unregisterHTMLEditors();
			
			// show the article categories and lists
			document.getElementById("editor-pane").style.display = "none";
			document.getElementById("content-pane").style.display = "table";
		};
		
		var query = "action=edit_article&id=" + id;
		pageManager.post('ajax_pages/articles.php', query, '#editor-pane #pane-content', function(result) {
			// hide the content pane and show the editor
			document.getElementById("content-pane").style.display = "none";
			document.getElementById("editor-pane").style.display = "block";
			
			// setup the editor form
			setup_form();
			
			// add a listener for the cancel button
			pageManager.addEvent("#editor-pane #can-art-btn",'click',function() {
				cancel_form();	
			});
			
			pageManager.addEvent("#editor-pane #sav-art-btn",'click',function() {
				// ensure the tinyMCE editors save their content first
				tinyMCE.triggerSave();
				
				// run simple validation on the form
				if( !$p("#article-form").validate() ) {
					// prevent the dialog from closing if validation fails
					return false; 
				}
				
				var selected_cat_id = pageManager.$("#article-form #CategoryID").value;
				
				// build a query of the data for submission
				var query = "action=update_article&CategoryID=" + articles.category_id + "&" + $p("#article-form").serialize();
				
				// submit the data
				pageManager.post('ajax_pages/articles.php', query, 'pm-pane-content', function(data) {

					// hide the editor
					cancel_form();
					
					// reload the current category of articles
					articles.loadArticles( articles.lastCategoryLink );
				});
				
				// prevent the dialog from closing
				return false;
			});
			
		});
	},
	
	deleteArticle: function(article_id) {
		pageManager.showConfirmMessage({
			title: 'Confirm Article Delete',
			content: "Do you want to delete the specified articles from this site?",
			okButtonText: 'Continue Delete',
			okButtonAction: function() {
				var query = "action=delete_articles&article_ids=" + article_id;
                $p.post( articles.ajax_page, query, null, function(data) {
                    $p("#article-row-" + article_id ).remove();
                });
			}
		});
	},
	
	deleteArticles: function() {
		
		/**
         * it would have been so much easier to use the following selector
         * .cms-data-table td input[type=checkbox]:checked
         * but IE8 does not support the :checked pseudo class, so we will need to
         * do the checking manually in order to be cross platform compartible
         */
        var checked = articles.getCheckedArticles();
		
        if( checked.length == 0 ) {
            alert("Please Select Items To Delete");
            return;
        }
		
		pageManager.showConfirmMessage({
			title: "Confirm Article Deletion",
			content: "Do you want to delete the selected articles from this site?",
			okButtonText: "Delete Selected",
			okButtonAction: function(e) {
				var boxes = pageManager.all(".cms-data-table tr td input[type=checkbox]");
				var selected = [];
				
				for(var i = 0, j = 0; i < boxes.length; i++) {
					if( boxes[i].checked ) {
						selected[j++] = boxes[i].value;
					}
				}
				
				var query = "action=delete_articles&article_ids=" + selected;
                pageManager.post( articles.ajax_page, query, null, function() {
					for(var i = 0; i < selected.length; i++) {
                    	$p("#article-row-" + selected[i] ).remove();
					}
                });
			}
		});
	},
	
	moveArticlesToCategory: function(menuLink) {
        var selected = articles.getCheckedArticles();

        if( selected.length == 0 ) {
            alert("Please Select Articles To Be Moved");
            return;
        }

        var msg_ids = "";
        for(var i = 0; i < selected.length; i++) {
            msg_ids += selected[i].value;

            if( i < selected.length - 1 ) {
                msg_ids += ",";
            }
        }

        var query = "action=move_articles&category_id=" + menuLink.id + "&msg_ids=" + msg_ids;
		
        //pageManager.setLoaderMessage("Moving Selected Messages To <b>" + menuLink.innerHTML + "</b>");
        pageManager.post( articles.ajax_page, query, null, function(data) {
            articles.removeSelectedArticles();
        });
    },
	
	removeSelectedArticles: function() {
        // select all checkbox fields in table-cells in the data-table component
        pageManager.all(".cms-data-table td input[type=checkbox]", function(el) {
            if( el.checked ) {
                $p("#article-row-" + el.value ).remove();
            }
        });

        // if only header row remains, then add an instruction row
        if( pageManager.all(".cms-data-table tbody tr").length == 1 ) {

            var td = document.createElement("td");
                td.colSpan = 3;
                td.appendChild( document.createTextNode("No Articles Available In This Category") );

            var tr = document.createElement("tr");
                tr.appendChild(td);

            var table = pageManager.$(".cms-data-table tbody");
                table.appendChild(tr);

        }
    },
	
	publishArticle: function(pubLink) {
		var shdPublish = pubLink.className == 'cms-publish-link' ? false : true;
		
		var query = "action=publish_article&article_id=" + pubLink.id + "&publish=" + shdPublish;
		
		pageManager.post('ajax_pages/articles.php', query, null, function(result) {
			pubLink.className = shdPublish ? 'cms-publish-link' : 'cms-unpublish-link';
			pubLink.title = shdPublish ? 'Published (Click To Unpublish)' : 'Unpublished (Click To Publish Now)';
		});
	},
	
	registerHTMLEditors: function() {
		// initialize the tinymce library for summary and content fields
		ui.htmlContentEditor("ArticleContent");
		
		ui.htmlMiniEditor("ArticleSummary");
	},
	
	unregisterHTMLEditors: function() {
		try {
			tinyMCE.remove( tinyMCE.getInstanceById('ArticleSummary') );
			tinyMCE.remove( tinyMCE.getInstanceById('ArticleContent') );
		} catch(e) {}
	},
	
	getCheckedArticles: function() {
        var checks = pageManager.all(".cms-data-table td input[type=checkbox]");

        var checked = [];
        for(var i = 0, j = 0; i < checks.length; i++ ){
            if( checks[i].checked ) {
                checked[j++] = checks[i];
            }
        }

        return checked;
    },
	
	showDialogForAdd: function() {
		// add seo alias creator
		$("#CategoryName").friendurl({id:'CategoryAlias'});	
		
        pageManager.$('#cat-add-dialog .cms-dialog-title').innerHTML = "Add Category";
        pageManager.$('#cat-add-btn').value = 'Add Category';
		pageManager.all("#cat-add-dialog input[type=text], #cat-add-dialog textarea", function(el) {
			el.value = "";	
		});
        pageManager.$('#cat-add-btn').onclick = function() {
            articles.addCategory();
        };
        pageManager.show('#cat-add-dialog');
    },
	
	showDialogForEdit: function() {
		// remove seo alias creator
		$("#CategoryName").unbind('keyup');	
		
        var selected = articles.lastCategoryLink;
        var query = "action=load_category&category_id=" + selected.getAttribute('data-id');
        pageManager.post('ajax_pages/articles.php',query, null, function(data) {
			
			if(JSON) {
				
                var obj = JSON.parse(data);

                document.getElementById("CategoryName").value = obj.CategoryName;
                document.getElementById("CategoryDescription").value = obj.CategoryDescription;
                document.getElementById("CategoryAlias").value = obj.CategoryAlias;
                document.getElementById("Position").value = obj.Position;
                document.getElementById("ParentID").value = obj.ParentID;
				document.getElementById("id").value = obj.id;
				articles.lastCategoryParentID = obj.ParentID;
				
                pageManager.$('#cat-add-dialog .cms-dialog-title').innerHTML = "Edit Category Information";
                pageManager.$('#cat-add-btn').value = 'Save Changes';
                pageManager.$('#cat-add-btn').onclick = function() {
                    articles.updateCategory();
                };
				
                pageManager.show('#cat-add-dialog');
            }
        });
    },
	
	addCategory: function() {
		
        var valid = $p("#cat-add-form").validate({
            "CategoryName": "Category Name - Required",
            "CategoryDesc": "Category Description",
            "CategoryAlias": "Category Tag - Required"
        });
		
        if( !valid ) {
            return;
        }
		
        var query = "action=add_category&" + $p("#cat-add-form").serialize();
        pageManager.post( articles.ajax_page, query, null, function(data) {

			if(JSON) {
                var obj = $p.parseJSON(data);

                var a = document.createElement("a");
                a.id = obj.id;
                a.title = obj.CategoryDescription;
                a.setAttribute("href","#");
				a.setAttribute("data-id", obj.id );
                a.innerHTML = obj.CategoryName;
                a.onclick = function() {
                    //clear any previously selected list items
                    pageManager.all(".category-list li", function(li) {
                        li.className = '';
                    });
					
                    // load the articles in this category and indicate it as selected
                    articles.loadArticles( this );
					
                    return false;
                };
				
                var li = document.createElement("li");
				li.id = "cat-li-" + obj.id;
                li.appendChild(a);
				
				// if category has a parent
				if( obj.ParentID && obj.ParentID != '' ) {
					// check if parent has any children loaded
					var ul = pageManager.$(".category-list #cat-li-" + obj.ParentID + " ul" );
					// if a child list exists, simply append new item to list
					if( ul ) {
						ul.appendChild(li);	
					
					// create the child list, append the new child, and append the list to the parent
					} else {
						ul = document.createElement("UL");
						ul.appendChild(li);
						
						pageManager.$(".category-list #cat-li-" + obj.ParentID ).appendChild(ul);
					}
				
				// if no parent, then append new item to main list	
				} else {
                	pageManager.$(".category-list").appendChild(li);
				}
				
				// lastly add an option to the ParentID combo box
				var opt = document.createElement("option");
					opt.value = obj.id;
					opt.text = obj.CategoryName;
					
				// get the ParentID combobox
				var parent_ids = document.getElementById("ParentID");
				if( obj.ParentID && obj.ParentID != "" ) {
					// locate the parent element of this item in the combo box
					var parent_opt = pageManager.$("#ParentID #cat-id-" + obj.ParentID );
					
					// get the leading dashes before the parent element text
					var dashes = parent_opt.text.substring( 0, parent_opt.text.lastIndexOf("-") + 1 );
					
					// update the text of the new element with two more dashes than the parent
					// to indicate that it is a child element
					opt.text = dashes + "-- " + opt.text;
					
					// insert the new node before the parents next sibling
					parent_ids.insertBefore( opt, parent_opt.nextSibling );
				} else {
					parent_ids.appendChild( opt );
				}
			
            // if JSON does not exist natively, simply refresh the page and load the
            // categories from the database
            } else {
                history.go(0);
            }
			
            document.getElementById("cat-add-form").reset();
            pageManager.hide('cat-add-dialog');
        });
    },
	
    updateCategory: function() {
		
        var valid = $p("#cat-add-form").validate({
            "CategoryName": "Category Name - Required",
            "CategoryDesc": "Category Description",
            "CategoryTag": "Category Tag - Required"
        });
		
        if( !valid ) {
            return;
        }
		
        var lastCat = articles.lastCategoryLink;

        var query = "action=update_category&id=" + lastCat.getAttribute("data-id") + "&" + $p("#cat-add-form").serialize();
        pageManager.post( articles.ajax_page, query, null, function(data) {

            // retrieve the menu object information and update the link information
            // incase the titles or descriptions have been changed
            if(JSON) {
				
                var obj = $p.parseJSON(data);
                lastCat = articles.lastCategoryLink;
                lastCat.title = obj.CategoryDescription;
                lastCat.innerHTML = obj.CategoryName;
				
				// if the new Parent ID is not the same as the last parent ID before
				// the update, then attempt a repositioning
				if( articles.lastCategoryParentID != obj.ParentID ) {
					var li = lastCat.parentNode;
					
					if( obj.ParentID && obj.ParentID != "" ) {
						// find the new parent element
						var p_li = pageManager.$(".category-list #cat-li-" + obj.ParentID);	
						p_li.appendChild(li);
					} else {
						var p_li = pageManager.$(".category-list");
						p_li.appendChild(li);
					}
				}

            } else {
                history.go(0);
            }

            document.getElementById("cat-add-form").reset();
            pageManager.hide('cat-add-dialog');
        });
    },
	
	deleteArticleCategory: function() {
        var lastCat = articles.lastCategoryLink;
		var last_li = lastCat.parentNode;
		
        pageManager.showConfirmMessage({
            title: "Confirm News Category Delete",
            content: "This will delete all articles in the <b>" + lastCat.innerHTML + "</b> category. "
            + "Do you want to continue the delete of this category?",
			width: '400px',
            okButtonText: "Delete Category",
            okButtonAction: function() {
                var query = "action=delete_category&category_id=" + articles.lastCategoryLink.getAttribute("data-id") ;
                pageManager.post(articles.ajax_page, query, null, function(data) {
                    last_li.parentNode.removeChild( last_li );
                });
            }
        });
    }
};